package weaver.tools.util;

import com.alibaba.fastjson.JSONObject;
import weaver.conn.RecordSet;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.BaseBean;
import weaver.general.TimeUtil;
import weaver.upgradetool.wscheck.Util;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

/**
 * @Title: Ecology9
 * @Company: 泛微软件
 * @author: weaver.Dusongsong
 * @version: 1.0
 * @CreateDate: 2024-04-15
 * @Description: 建模工具类
 * @ModifyLog:
 **/

public class ModelUtil {

    /**
     *@Description: 建模权限重构
     */
    public static void newModeRight(int userid, int formmodeid, int id) {
        ModeRightInfo modeRightInfo = new ModeRightInfo();
        modeRightInfo.setNewRight( true );
        modeRightInfo.editModeDataShare( userid, formmodeid,id );
    }

    /**
     *@Description: 表单建模数据插入
     */
    public int insertModelData(String tablename, Map<String, Object> map) {
        int dataid = 0;
        RecordSet rs = new RecordSet();
        String uuid = UUID.randomUUID().toString();
        int formmodeid = getFormmodeid(tablename);
        String insSql = "insert into " + tablename
                + "(modeuuid,modedatacreater,modedatacreatedate,modedatacreatetime,formmodeid)values(?,?,?,?,?)";
        Object[] params = {uuid, 1, TimeUtil.getCurrentDateString(), TimeUtil.getOnlyCurrentTimeString(), formmodeid};
        if (rs.executeUpdate(insSql, params)) {
            dataid = ModeUUID2DataId(tablename,uuid);
            if (dataid > 0) {
                //遍历数据 进行update
                StringBuilder updatesql = new StringBuilder("update " + tablename + " set ");
                Set<String> keySet = map.keySet();
                for (String key : keySet) {
                    updatesql.append(key).append("='").append(map.get(key)).append("',");
                }
                if (updatesql.toString().endsWith(",")) {
                    updatesql = new StringBuilder(updatesql.substring(0, updatesql.length() - 1));
                    updatesql.append(" where id=").append(dataid);
                    rs.executeUpdate(updatesql.toString());
                }
                //进行权限重构
                newModeRight(1, formmodeid, dataid);
            }
        }
        return dataid;
    }

    /**
     *@Description: 表单建模数据更新
     */
    public boolean updateModelData(String tablename, int dataid, JSONObject paramJson) {
        RecordSet rs = new RecordSet();
        BaseBean baseBean = new BaseBean();
        String updatesql = "update " + tablename + " set  ";
        StringBuilder valuesStr = new StringBuilder();
        Map<String, Object> map = JSONObject.toJavaObject(paramJson, Map.class);
        Set<String> keySet = map.keySet();
        for (String key : keySet) {
            if (valuesStr.toString().equals("")) {
                valuesStr = new StringBuilder(key + "='" + map.get(key) + "'");
            } else {
                valuesStr.append(",").append(key).append("='").append(map.get(key)).append("'");
            }
        }
        updatesql += valuesStr + " where id='" + dataid + "'";
        baseBean.writeLog(">>>>>updateModelData>>>>updatesql=" + updatesql);
        return rs.execute(updatesql);
    }

    /**
     *@Description: 根据建模表名和UUID获取数据ID 常用于建模的权限重构获取数据ID
     */
    public static int ModeUUID2DataId(String tablename,String uuid){
            RecordSet rs = new RecordSet();
            rs.executeQuery("select id from " + tablename + " where modeuuid =?",uuid);
            rs.next();
            return Util.getIntValue(rs.getString(1));
    }

    /**
     *@Description: 根据建模的字段名称获取字段ID
     */
    public static Map<String,String> getModeFieldId(int formid, String num) {
        formid = Math.abs(formid);
        String sql = "";
        if ("0".equals(num)) {
            sql = "select b.id,fieldname,detailtable from workflow_billfield b ,modeinfo a where b.billid=-"
                    + formid
                    + " and a.formid=b.billid and (detailtable is null or detailtable = '') ";
        } else {
            sql = "select b.id,fieldname,detailtable from workflow_billfield b ,modeinfo a where b.billid=-"
                    + formid
                    + " and a.formid=b.billid and detailtable='formtable_main_"
                    + formid + "_dt" + num + "'";
        }
        RecordSet rs = new RecordSet();
        rs.execute(sql);
        Map<String,String> array = new HashMap<String,String>();
        while (rs.next()) {
            array.put(
                   Util.null2String(rs.getString("fieldname")).toLowerCase(),
                   Util.null2String(rs.getString("id")));
        }
        return array;
    }

    /**
     *@Description: 获取建模Id
     */
    private static int getFormmodeid(String tablename) {
        RecordSet rs = new RecordSet();
        String sql = "select m.id from modeinfo m left join WORKFLOW_BILL b on m.formid = b.id where b.tablename = ?";
        rs.executeQuery(sql, tablename);
        rs.next();
        return weaver.general.Util.getIntValue(rs.getString("id"));
    }

    /**
     *@Description: 获取主表表数据
     */
    public Map<String, Object> getMainField(JSONObject returnJson, String formid) {
        RecordSet rs = new RecordSet();
        Map<String, Object> map = new HashMap<>();
        rs.executeQuery("select fieldname from workflow_billfield where billid=? and viewtype=0", formid);
        while (rs.next()) {
            String fieldname = Util.null2String(rs.getString("fieldname")).toUpperCase();
            if (returnJson.containsKey(fieldname)) {
                map.put(fieldname, returnJson.getString(fieldname));
            }
        }
        return map;
    }

    /**
     *@Description: 获取明细表数据
     */
    public Map<String, Object> getDetailField(JSONObject returnJson, String formid, String deltablename) {
        RecordSet rs = new RecordSet();
        Map<String, Object> map = new HashMap<>();
        rs.executeQuery("select fieldname from workflow_billfield where billid=? and viewtype=1 and detailtable=?", formid, deltablename);
        while (rs.next()) {
            String fieldname = weaver.general.Util.null2String(rs.getString("fieldname")).toUpperCase();
            if (returnJson.containsKey(fieldname)) {
                map.put(fieldname, returnJson.getString(fieldname));
            }
        }
        return map;
    }

}
